<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\facade\Session;

class SubmitParam extends \think\Model
{
    const SET_TYPE = [
        1 => '单文本',
        2 => '多文本',
        3 => '图片',
    ];
    
    const ALLOW_KEY = [
        'tel',
        'user_name',
        'image1',
        'image2',
        'image3',
    ];

    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        return $this->where([['id', '=', $id]])->find();
    }

    /**
    * 通过任务id获取参数
    * @param task_id int
    * @return array
    */
    public function _getList($task_id){
        return $this->where([['task_id', '=', $task_id]])->select()->toArray();
    }
    
    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['title', '=', $name]])->find();
    }
    
    //校验用户名是否存在
    public function _checkName($value, $sid){
        $model = new Submit;
        $submit = $model->_findOne($sid);
        if(empty($submit)){
            $this->error = '任务信息异常';
            return false;
        }
        
        $task_id = $submit['task_id'];
        
        $data = $this->where([['title', '=', $value], ['task_id', '=', $task_id]])->find();
        if(!empty($data)){
            $this->error = '标题已存在';
            return false;
        }
        return true;
    }
    
    /**
    * 校验key是否唯一
    * @param value string 关键字
    * @param sid int 信息（submit）表id
    * @return bool
    */
    public function _checkKey($value, $sid){
        $model = new Submit;
        $submit = $model->_findOne($sid);
        if(empty($submit)){
            $this->error = '任务信息异常';
            return false;
        }
        
        $task_id = $submit['task_id'];
        
        $data = $this->where([['skey', '=', $value],  ['task_id', '=', $task_id]])->find();
        if(!empty($data)){
            $this->error = '关键字已存在';
            return false;
        }
        return true;
    }
    

    /**
    * 校验是否被冻结
    */
    public function _checkStatus($id){
        $data = $this->where(array('id'=>$id, 'status'=>1))->find();
        if(empty($data)){
            $this->error = '已禁用';
            return false;
        }
        return true;
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->order($order_by);
        $result = get_page($obj, $condition, $page_size);
       
        return $result;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
        $title = trim($post['title']);
        $sid = (int)$post['sid'];
        $admin = $this->where([['title', '=', $title],['sid', '=', $sid]])->find();
        if($admin){
            $this->error = '已存在';
            return false;
        }
        
        $model = new Submit;
        $submit = $model->_findOne($sid);
        if(empty($submit)){
            $this->error = '任务信息异常';
            return false;
        }
        
        $key = filterXss($post['skey']);
        
        if(!in_array($key, self::ALLOW_KEY)){
            $this->error = '关键字错误';
            return false;
        }
        
        $insert = [
            'type' => (int)$post['type'],
            'task_id' => $submit['task_id'],
            'sid' => (int)$post['sid'],
            'skey' => $key,
            'title' => $title,
            'content' => $post['content'],
            'sort' => (int)$post['sort'],
            'created' => time(),
            'updated' => time(),

        ];
        if(!$this->insert($insert)){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此';
            return false;
        }

        if(!$result->delete()){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }
    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->delete();
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $id = $post['id'];
        $result = $this->_findOne($id);
        if(empty($result)){
            $this->error = '不存在';
            return false;
        }
        $sid = $result['sid'];
        
        $model = new Submit;
        $submit = $model->_findOne($sid);
        if(empty($submit)){
            $this->error = '任务信息异常';
            return false;
        }
        
        $key = filterXss($post['skey']);
        
        if(!in_array($key, self::ALLOW_KEY)){
            $this->error = '关键字错误';
            return false;
        }
        
        $task_id = $submit['task_id'];
        $data = $this->where([['title', '=', trim($post['title'])],['task_id', '=', $task_id]])->find();
        //var_dump($data);die;
        if(!empty($data)){
            if($data->id != $result->id){
                $this->error = '标题已存在';
                return false;
            }
        }
        

        
        $data = $this->where([['skey', '=', trim($post['skey'])],['task_id', '=', $task_id]])->find();
        //var_dump($data);die;
        if(!empty($data)){
            if($data->id != $result->id){
                $this->error = '关键字已存在';
                return false;
            }
        }
        
        $model = new Submit;
        $submit = $model->_findOne($sid);
        if(empty($submit)){
            $this->error = '任务信息异常';
            return false;
        }

        
        $result->task_id = $submit['task_id'];
        
        $update = [
            'task_id' => $submit['task_id'],
            'title' => trim($post['title']),
            'skey' => trim($post['skey']),
            'content' => $post['content'],
            'sort' => intval($post['sort']),
            'type' => intval($post['type']),
            'updated' => time(),
        ];

        $ret =$this->where([['id', '=', $id]])->update($update);
        //var_dump($ret);die;
        if($ret === false){
            $this->error = '操作失败';
            return false;
        }
        
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "停用成功";
            $error = "停用失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        
        return true;
    }
    



    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('u')->where($where)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $sid = isset($request['sid']) ? $request['sid'] : '';
        $type = isset($request['type']) ? $request['type'] : '';
        $title = isset($request['title']) ? $request['title'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['title'] = $title;
        $request['type'] = $type;
        
        $search = $request;
        
        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['title'])));
        $request['title'] = str_replace('%', "\%", $title);
        
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "u.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "u.created <= $end and ";
            }elseif($k == 'title'){
                $where .= "u.title like '%$v%' and ";
            }elseif($k == 'type'){
                $where .= "u.type = $v and ";
            }elseif($k == 'sid'){
                $where .= "u.sid = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }
}